package sqcon.sql;

import java.util.ArrayList;
import java.util.NoSuchElementException;
import sqcon.util.StringParsingException;
import sqcon.util.StringTokenParser;

public class FromClause implements Clause{
	private static final ClauseType type = ClauseType.FROM;
	
	private ArrayList<Table> tableList;
	
	public FromClause(){
		tableList = new ArrayList<Table>();
	}
	
	public FromClause(String clauseString) throws ConstructSqlException{
		StringTokenParser stp = new StringTokenParser(clauseString);
		try{
			if(!stp.nextToken().equalsIgnoreCase(ClauseType.FROM.toString())){
				throw new ConstructSqlException("From Clause Parsing Error");
			}
			
			setFromContent(stp.getRest());
			
		}catch(StringParsingException e){
			throw new ConstructSqlException("From Clause Parsing Error");
		}catch(NoSuchElementException e){
			throw new ConstructSqlException("From Clause Parsing Error");
		}
	}
	
	public void addTable(Table table){
		tableList.add(table);
	}
	
	public ArrayList<Table> getTableList(){
		return tableList;
	}
	
	public ClauseType getClauseType(){
		return type;
	}
	
	public String printString(){
		String ret = "FROM";
		String tableListStr = "";
		for(Table table : tableList){
			tableListStr = tableListStr + ", " + table.toString();
		}
		
		return ret + tableListStr.substring(2);
	}
	
	private void setFromContent(String contentStr) throws ConstructSqlException{
		StringTokenParser stp = new StringTokenParser(contentStr, ",", true);
		
		try{
			while(stp.hasMoreTokens()){
				tableList.add(Table.generateTable(stp.nextToken()));
			}
		}catch(StringParsingException e){
			throw new ConstructSqlException("Error parsing from clause");
		}
	}
}
